/**
 * 
 */
package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

/**
 * @author leiruiqi
 *
 */
public class FileCopy {

	public static void main(String[] args) {
		String fromFileName = args[0];
		FileCopy fc = new FileCopy();
		fc.backupFile(fromFileName);
	}
	
	public void initPath(String path){
		File file = new File(path);
		if(!file.exists()){
			file.mkdirs();
		}
	}
	public void backupFile(String fileName){
		
		String backupPath = "backup/";	
		initPath(backupPath);
		String uploadPath  = "upload/";
		initPath(uploadPath);
		
		File fromfile = new File(uploadPath+fileName);
		if(!(fromfile.exists()&&fromfile.isFile())){
			return;
		}
		File tofile  = new File(backupPath+fileName);
		try {
			if(!tofile.exists()){
				tofile.createNewFile();
			}
			copyFileforJava(fromfile,tofile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	public void saveFile(File file){
		
	}
	
	public static long copyFileforJava(File f1, File f2) throws Exception {
		long time = new Date().getTime();
		int length = 2097152;
		FileInputStream in = new FileInputStream(f1);
		FileOutputStream out = new FileOutputStream(f2);
		byte[] buffer = new byte[length];
		while (true) {
			int ins = in.read(buffer);
			if (ins == -1) {
				in.close();
				out.flush();
				out.close();
				return new Date().getTime() - time;
			} else
				out.write(buffer, 0, ins);
		}
	}
}
